package vsm.vsm_server.controller;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import vsm.vsm_server.pojo.Result.Result;
import vsm.vsm_server.pojo.Result.ResultEnum;
import vsm.vsm_server.pojo.User.Record.Like.LikeVideo;
import vsm.vsm_server.pojo.Video.*;
import vsm.vsm_server.service.*;

import java.math.BigInteger;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static vsm.vsm_server.component.oss.InitAcsClint.*;

@Slf4j
@RestController
@RequestMapping("/video")
@CrossOrigin
public class VideoController {


    @Autowired
    private StringRedisTemplate redisTemplate; // 注入 Redis 模板

    @Autowired
    private VideoService videoService;

    @Autowired
    private VodService vodService;

    @Autowired
    private RelationService relationService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private HistoryService historyService;
    /*
    根据userid获取其发布视频
     */
    @GetMapping("/getSelf/{userid}")
    public Result<List<VideoNailVO>> getSelfVideos(@PathVariable BigInteger userid) {
        List<VideoNailVO> videoNailVOList = videoService.getSelfVideos(userid);
        return Result.success(videoNailVOList);
    }

    /*
      根据userid获取其喜欢视频
     */
    @GetMapping("/getLikeVideos/{userid}")
    public Result<List<VideoNailVO>> getLikeVideos(@PathVariable BigInteger userid){
        List<VideoNailVO> videoNailVOList =  likeService.getLikeVideos(userid);
        return Result.success(videoNailVOList);
    }
    /*
      根据userid获取其历史观看视频
     */
    @GetMapping("/getHistoryVideos/{userid}")
    public Result<List<VideoHistoryVO>> getHistoryVideos(@PathVariable BigInteger userid){
        log.info("user:{}，获取历史视频",userid);
        List<VideoHistoryVO> videohistoryVOList =  historyService.getHistoryVideos(userid);
        return Result.success(videohistoryVOList);
    }

/*    *//*
    根据videoId 获取视频信息
     *//*
    @GetMapping("/getVideo/{userid}/{videoId}")
    public Result<VideoRecVO> getVideo(@PathVariable BigInteger userid, @PathVariable BigInteger videoId){
        //根据videoId获取video信息
        Video video = videoService.getVideo(videoId);
        if(video==null)
            return Result.error_special(ResultEnum.VIDEO_NOT_EXIST);
        VideoRecVO videoRecVO = videoService.videoToRecVideo(video,userid);
        return  Result.success(videoRecVO);
    }*/

    /*
    根据videoId 获取视频信息
     */
    @GetMapping("/getVideo/{userid}/{videoId}")
    public Result<VideoDetailVO> getVideoDetail(@PathVariable BigInteger userid, @PathVariable BigInteger videoId){
        //根据videoId获取video信息
        Video video = videoService.getVideo(videoId);
        if(video==null)
            return Result.error_special(ResultEnum.VIDEO_NOT_EXIST);
        VideoDetailVO videoDetailVO = videoService.videoToDetailVideo(video,userid);
        return  Result.success(videoDetailVO);
    }

    /*
    获取推荐视频列表
     */
    @GetMapping("/getRecVideoList/{userid}/{videocount}")
    public Result<List<VideoIdVO>> getRecVideoList(@PathVariable BigInteger userid, @PathVariable Integer videocount){
        log.info("用户：{},获取推荐视频,数量为：{}", userid, videocount);
        List<VideoIdVO> videoList = videoService.getRecVideoList(userid,videocount);
        return Result.success(videoList);
    }
/*
    @GetMapping("/getRecVideos/{userid}/{videocount}")
    public Result<List<VideoRecVO>> getRecVideos(@PathVariable BigInteger userid, @PathVariable Integer videocount) {
        log.info("用户：{},获取推荐视频,数量为：{}", userid, videocount);
        List<Video> videoList = videoService.getRecVideos(userid, videocount);
        List<VideoRecVO> videoRecList = new ArrayList<>();

        for (Video v : videoList) {
            VideoRecVO videoRec = videoToRecVideo(v,userid);
            videoRecList.add(videoRec);
        }
        return Result.success(videoRecList);


    }*/

    /*
    根据id获取视频url
     */
    @GetMapping("/getUrl/{videoId}")
    public Result<VideoUrlVO> getUrl(@PathVariable String videoId) {
        VideoUrlVO playUrl = vodService.getUrl(videoId);
        if (playUrl != null) {
            return Result.success(playUrl);
        } else {
            return Result.error_special(ResultEnum.VIDEO_URL_NOT_EXIST);
        }

    }

    /*
   根据id获取视频凭证
    */
    @GetMapping("/getAuth/{videoId}")
    public Result<String> getAuth(@PathVariable String videoId) {
        String playAuth = vodService.getAuth(videoId);
        if (playAuth != null) {
            return Result.success(playAuth);
        } else {
            return Result.error_special(ResultEnum.VIDEO_URL_NOT_EXIST);
        }

    }

    /*
    获取凭证
     */
    @PostMapping("/create")
    public Result<CreateUploadVideoResponse> create(@RequestBody VideoCreateDTO videoCreateDTO) {
        String accessKeyId = "LTAI5tEdXUnEBu5V7sQVnkJs";
        String accessKeySecret = "PRYEoatScwy8LlRROPbaRJ0DYxtdr9";
        try {
            DefaultAcsClient client = initVodClient(accessKeyId, accessKeySecret);
            CreateUploadVideoResponse response = new CreateUploadVideoResponse();
            log.info(videoCreateDTO.toString());
            response = createUploadVideo(client, videoCreateDTO);
            System.out.print("VideoIdVO = " + response.getVideoId() + "\n");
            System.out.print("UploadAddress = " + response.getUploadAddress() + "\n");
            System.out.print("UploadAuth = " + response.getUploadAuth() + "\n");
            System.out.print("RequestId = " + response.getRequestId() + "\n");
            String videoPath = response.getVideoId();
            if (videoPath != null && !videoPath.isEmpty()) {
                String s = JSON.toJSONString(videoCreateDTO);
                String redisKey = "video_upload_info:" + videoPath;
                redisTemplate.opsForValue().set(redisKey, s, 1, TimeUnit.HOURS); //1h 过期
            } else {
                log.error("VOD 返回的 VideoIdVO 为空，无法暂存信息");
                throw new Exception();
            }
            return Result.success(response);
        } catch (Exception e) {
            System.out.print("ErrorMessage = " + e.getLocalizedMessage());
            return Result.error_special(ResultEnum.OSS_UP_WRONG);
        }

    }

    /*
   刷新凭证
    */
    @GetMapping("/refresh/{videoid}")
    public Result<RefreshUploadVideoResponse> refresh(@PathVariable String videoid) {
        String accessKeyId = "LTAI5tEdXUnEBu5V7sQVnkJs";
        String accessKeySecret = "PRYEoatScwy8LlRROPbaRJ0DYxtdr9";
        try {
            DefaultAcsClient client = initVodClient(accessKeyId, accessKeySecret);
            RefreshUploadVideoResponse response = new RefreshUploadVideoResponse();
            response = refreshUploadVideo(client, videoid);
            System.out.print("VideoIdVO = " + response.getVideoId() + "\n");
            System.out.print("UploadAddress = " + response.getUploadAddress() + "\n");
            System.out.print("UploadAuth = " + response.getUploadAuth() + "\n");
            System.out.print("RequestId = " + response.getRequestId() + "\n");
            return Result.success(response);
        } catch (Exception e) {
            System.out.print("ErrorMessage = " + e.getLocalizedMessage());
            return Result.error_special(ResultEnum.OSS_UP_WRONG);
        }

    }
}
